'use strict';

const RouterService = require('../base');

class UserPostLikeService extends RouterService {
    static get modelName() {
        return 'Business.UserPostLike';
    }

    /**
     * 点赞动态
     * @param {number} postId - 动态ID
     * @param {number} userId - 用户ID
     */
    async like(postId, userId) {
        const { ctx } = this;
        
        // 检查动态是否存在
        const post = await ctx.model.Business.UserPost.findByPk(postId);
        if (!post) {
            throw new Error('动态不存在');
        }

        // 检查用户是否存在
        const user = await ctx.model.Business.User.findByPk(userId);
        if (!user) {
            throw new Error('用户不存在');
        }

        // 检查是否已经点赞
        const existingLike = await ctx.model.Business.UserPostLike.findOne({
            where: {
                post_id: postId,
                user_id: userId,
                status: 1,
                deleted: 0
            }
        });

        if (existingLike) {
            throw new Error('您已经点赞过这条动态');
        }

        // 使用事务确保数据一致性
        const result = await ctx.model.transaction(async (t) => {
            // 创建点赞记录
            const likeRecord = await ctx.model.Business.UserPostLike.create({
                post_id: postId,
                user_id: userId,
                status: 1
            }, { transaction: t });

            // 更新动态的点赞数量
            await ctx.model.Business.UserPost.increment('like_count', {
                where: { id: postId },
                transaction: t
            });

            return likeRecord;
        });

        return result;
    }

    /**
     * 取消点赞
     * @param {number} postId - 动态ID
     * @param {number} userId - 用户ID
     */
    async unlike(postId, userId) {
        const { ctx } = this;
        
        // 检查动态是否存在
        const post = await ctx.model.Business.UserPost.findByPk(postId);
        if (!post) {
            throw new Error('动态不存在');
        }

        // 检查用户是否存在
        const user = await ctx.model.Business.User.findByPk(userId);
        if (!user) {
            throw new Error('用户不存在');
        }

        // 查找点赞记录
        const existingLike = await ctx.model.Business.UserPostLike.findOne({
            where: {
                post_id: postId,
                user_id: userId,
                status: 1,
                deleted: 0
            }
        });

        if (!existingLike) {
            throw new Error('您还没有点赞这条动态');
        }

        // 使用事务确保数据一致性
        const result = await ctx.model.transaction(async (t) => {
            // 更新点赞记录状态为已取消
            await ctx.model.Business.UserPostLike.update(
                { status: 0 },
                {
                    where: { id: existingLike.id },
                    transaction: t
                }
            );

            // 减少动态的点赞数量
            await ctx.model.Business.UserPost.decrement('like_count', {
                where: { id: postId },
                transaction: t
            });

            return { success: true };
        });

        return result;
    }

    /**
     * 获取用户的点赞状态
     * @param {number} postId - 动态ID
     * @param {number} userId - 用户ID
     */
    async getUserLikeStatus(postId, userId) {
        const { ctx } = this;
        
        const likeRecord = await ctx.model.Business.UserPostLike.findOne({
            where: {
                post_id: postId,
                user_id: userId,
                status: 1,
                deleted: 0
            }
        });

        return {
            isLiked: !!likeRecord,
            likeId: likeRecord ? likeRecord.id : null
        };
    }

    /**
     * 获取动态的点赞用户列表
     * @param {number} postId - 动态ID
     * @param {Object} options - 查询选项
     */
    async getPostLikes(postId, options = {}) {
        const { ctx } = this;
        
        const { page = 1, limit = 20 } = options;
        const offset = (page - 1) * limit;

        const result = await ctx.model.Business.UserPostLike.findAndCountAll({
            where: {
                post_id: postId,
                status: 1,
                deleted: 0
            },
            include: [
                {
                    model: ctx.model.Business.User,
                    as: 'user',
                    attributes: ['id', 'nickname', 'avatar_url']
                }
            ],
            order: [['create_time', 'DESC']],
            limit,
            offset
        });

        return {
            list: result.rows,
            total: result.count,
            page,
            limit
        };
    }
}

module.exports = UserPostLikeService; 